<?php

/**
 * UploadForm class.
 */
class UploadForm extends CFormModel
{
	public $filename;
	public $message;
	public $type;
	public $userName;
	public $userId;

	/**
	 * Declares the validation rules.
	 * The rules state that username and password are required,
	 * and password needs to be authenticated.
	 */
	public function rules()
	{
		return array(
			// username and password are required
			array('type', 'required'),
			array('filename', 'checkUpload'),
			array('userName', 'checkUser'),
			array('message', 'length', 'max' => Yii::app()->params["maxTextSize"]),
			array('filename', 'file', 
				'types'=>'jpg,jpeg,png,gif,txt,doc,docx',
				'maxSize'=>1024*1024*Yii::app()->params["maxFileSize"],
				'allowEmpty'=>true
			),
			array('type, message', 'safe'),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'filename' => Yii::t('module_file', 'Filename'),
			'message' => Yii::t('module_file', 'Message'),
			'userName' => Yii::t('module_file', 'Recipient'),
		);
	}
	
	public function checkUser($attribute, $params)
	{
		if (Yii::app()->user->isGuest)
		{
			CValidator::createValidator('required', $this, 'userName')->validate($this);
		}
		
		if (!$this->userName)
		{
			$this->userId = Yii::app()->user->id;
			return true;
		}
		
		$userData = User::model()->getUserByName($this->userName);
		if (!$userData)
		{
			$this->addError("userName", Yii::t('module_user', 'User not found'));
			return false;
		}
		
		$this->userId = $userData["id"];
	}
	
	
	public function checkUpload($attribute, $params)
	{
		if (empty($this->filename) && empty($this->message))
		{
			CValidator::createValidator('required', $this, 'filename, message')->validate($this);
		}
	}
}
